var logger = require("pomelo-logger").getLogger(__filename);

module.exports = function (app) {
    return new MailRemote(app);
};

var MailRemote = function (app) {
    this.app = app;
};

MailRemote.prototype.sendMail = function (msg, callback) {
    logger.info("send mail msg=" + JSON.stringify(msg));
    if (!msg.hasOwnProperty("title")) {
        callback({resultCode: 404, message: "title为空"});
        return;
    }
    var title = msg["title"];

    if (!msg.hasOwnProperty("content")) {
        callback({resultCode: 404, message: "content为空"});
        return;
    }
    var content = msg["content"];

    var award = {};
    if (msg.hasOwnProperty("amount")) {
        let amount = msg["amount"];
        amount = parseInt(amount);
        if (amount >= 0 && amount <= 10000) {
            award['currencyType'] = msg["currencyType"];
            award['amount'] = amount;
        } else {
            callback({resultCode: 404, message: "只能发0-10000的礼包"});
            return;
        }
    }

    if (!msg.hasOwnProperty("sender")) {
        callback({resultCode: 404, message: "sender为空"});
        return;
    }
    var sender = msg["sender"];

    if (!msg.hasOwnProperty("receiverUids")) {
        callback({resultCode: 404, message: "receiverUids是空"});
        return;
    }

    var mailType = msg["type"];
    var receiverUids = msg["receiverUids"].split(",");

    var mailDataService = this.app.get("mailDataService");
    var self = this;
    mailDataService.addMailData(title, mailType, content, award, sender, receiverUids, function (mailData) {
        if (!!mailData) {
            var playerService = self.app.get("playerService");
            logger.info("send mail playerService" + JSON.stringify(mailData));
            playerService.sendMail(mailData);
            callback({resultCode: 0, message: "ok"});
        } else {
            callback({resultCode: 404, message: "add mail failed"});
        }
    });
};
